package mt.demo.service.news;

import mt.demo.dao.NewsDao;
import mt.demo.domain.NewsDomain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * Created by watson on 2015/9/24.
 */
@Service
public class NewsService {
    @Autowired
    private NewsDao newsDao;

    /**
     * 查找新闻
     *
     * @param newsDomain
     * @return
     */
    public List<NewsDomain> getDomain(NewsDomain newsDomain) {
        List<NewsDomain> domains = newsDao.getDomainByCondition(newsDomain);
        return domains;
    }

    /**
     * 增加新闻
     */

    public void CreateDomain(NewsDomain newsDomain) {
        //判断整个实体类是否存在要通过LIst接受
        NewsDomain condition = new NewsDomain();
        condition.setNewsName(newsDomain.getNewsName());
        List<NewsDomain> newsDomains = newsDao.getDomainByCondition(condition);
        if (newsDomains.size() == 0) {
            newsDao.addDomain(newsDomain);
        }

    }

    /**
     * 删除新闻
     */
    public void DelDomain(int id){
        NewsDomain newsDomain=newsDao.getDomainById(id);
        if (newsDomain!=null){
            newsDao.deleteDomain(newsDomain);
        }
    }

    /**
     * 保存图片
     */
    public void SavePicture(MultipartFile file){
        String fileName=null;
        String fileDir=null;
        if (!file.isEmpty()){
            //设置文件的名称
            fileName="wat"+ "." + FileHelper.getExtensionName(file.getOriginalFilename());
            //取得文件的绝对路径，WebRoot是配置的系统路径,在xml里面要声明
            fileDir = new File(System.getProperty("webroot","img/picture")).getAbsolutePath();
            try {
                //将multipartFile转换为file类型
                file.transferTo(new File(fileDir,fileName));
            }
            catch (Exception e){
                fileName = null;
            }
        }
    }
}
